#!/user/bin/env python3
# -*- coding: utf-8 -*-
"""
--------------------------------------
    Author:     JiChao_Song
    Date  :     2021/11/29 20:39
    Desc  :
--------------------------------------
"""
from functools import wraps

from django_http_log.common.response import CommonResponse

from common.enums.response_enums import CommonResultEnums
from common.utils.log_utils import logger
from common.utils.token_utils import AccessTokenUtil
from person.models import Project


def isAuthentication(flag=True):
    def view_decorator(func):
        @wraps(func)
        def wrapper(request, *args, **kwargs):
            token = request.headers.get('Accesstoken')
            if token is None or token == '':
                return CommonResponse(codeEnums = CommonResultEnums.TOKEN_INVALID)
            if AccessTokenUtil.verify_token(token) is None and flag:
                return CommonResponse(codeEnums = CommonResultEnums.TOKEN_INVALID)
            return func(request, *args, **kwargs)

        return wrapper

    return view_decorator


def Authentication(flag=True, isProject=False):
    def view_decorator(func):
        @wraps(func)
        def wrapper(self, request, *args, **kwargs):
            token = request.headers.get('Accesstoken')
            project = request.headers.get('Project')
            if flag:
                if token is None or token == '':
                    return CommonResponse(codeEnums = CommonResultEnums.TOKEN_INVALID)
                if AccessTokenUtil.verify_token(token) is None:
                    return CommonResponse(codeEnums = CommonResultEnums.TOKEN_INVALID)
                if isProject and (project is None or project == '' or project == 'undefined'):
                    return CommonResponse(codeEnums = CommonResultEnums.PROJECT_EXCEPTION)

            return func(self, request, *args, **kwargs)

        return wrapper

    return view_decorator
